import { Faction } from '../contexts/GameContext';

const ABILITIES = {
  ming: {
    name: '长城箭雨',
    description: '对所有敌方单位造成15点伤害',
    cost: { dragonVein: 1 },
    effect: (gameState: any) => {
      if (!gameState || !gameState.units) {
        return { units: [] };
      }
      const units = Array.isArray(gameState.units) ? gameState.units : [];
      return {
        units: units.map((unit: any) => {
          if (unit.owner !== gameState.currentPlayer?.id) {
            return { ...unit, health: unit.health - 15 };
          }
          return unit;
        })
      };
    }
  },
  mongol: {
    name: '草原狼群',
    description: '所有骑兵单位攻击力+5，持续2回合',
    cost: { dragonVein: 1 },
    effect: (gameState: any) => {
      if (!gameState) {
        return { units: [], effects: [{ type: 'mongol_buff', duration: 2 }] };
      }
      const units = Array.isArray(gameState.units) ? gameState.units : [];
      const effects = Array.isArray(gameState.effects) ? gameState.effects : [];
      return {
        units: units.map((unit: any) => {
          if (unit.owner === gameState.currentPlayer?.id && unit.type === 'cavalry') {
            return { ...unit, attack: unit.attack + 5 };
          }
          return unit;
        }),
        effects: [...effects, { type: 'mongol_buff', duration: 2 }]
      };
    }
  },
  korea: {
    name: '火牛阵',
    description: '对单个目标造成30点伤害',
    cost: { dragonVein: 1 },
    effect: (targetId: string, gameState: any) => {
      return {
        units: gameState.units.map((unit: any) => {
          if (unit.id === targetId) {
            return { ...unit, health: unit.health - 30 };
          }
          return unit;
        })
      };
    }
  },
  japan: {
    name: '夜袭',
    description: '立即获得一次额外攻击机会',
    cost: { dragonVein: 1 },
    effect: (gameState: any) => {
      return {
        canAttackAgain: true
      };
    }
  }
};

class SpecialAbilities {
  static getAbility(factionId: string) {
    return ABILITIES[factionId as keyof typeof ABILITIES];
  }

  static canUseAbility(factionId: string, resources: any) {
    const ability = this.getAbility(factionId);
    return resources.dragonVein >= ability.cost.dragonVein;
  }

  static useAbility(factionId: string, gameState: any, targetId?: string) {
    const ability = this.getAbility(factionId);
    if (!this.canUseAbility(factionId, gameState.resources)) {
      throw new Error('Not enough resources');
    }
    
    const newState = { ...gameState };
    newState.resources.dragonVein -= ability.cost.dragonVein;
    
    const effectResult = ability.effect(targetId || null, newState);
    return { ...newState, ...effectResult };
  }
}

export default SpecialAbilities;
